<?php

/**
 * PropertyController
 * 
 * @author Martin Bianculli
 * @version 0.1
 */
require_once 'Zend/Controller/Action.php';

class PropertyController extends Zend_Controller_Action {   

    public function init() {
        $ajax_actions = array('index', 'marker', 'search');
        if (in_array($this->getRequest()->getActionName(), $ajax_actions)) {
            if (!$this->getRequest()->isXmlHttpRequest()) throw new Exception('Invalid method'); 
        }        
        $ajaxContext = $this->_helper->getHelper('AjaxContext');
        foreach ($ajax_actions as $ajax_action) $ajaxContext->addActionContext($ajax_action, 'json');
        $ajaxContext->initContext();        
    }
    
    /**
     * The default action
     */
    public function indexAction() {
    	$this->setMarkers(Zend_Registry::get('em')->getRepository('Model_Property')->findAll());   	    	
    }
    
    public function markerAction() {
        $id = $this->getRequest()->getPost('id');
        $property  = Model_Property::find($id);
        if ($property) $this->view->desc = $property->desc;        
    } 
    
    public function searchAction() {
    	$this->setMarkers(Model_Property::filter($this->getRequest()->getPost()));        
    }
    
    private function setMarkers($properties) {
        $markers = array();
        foreach ($properties as $property) {
    		$markers[] = array(
    			'lat' => $property->coord->getLatitude(), 
    			'lng' => $property->coord->getLongitude(),
    			'id' => $property->id,
    		);    		
    	}
    	$this->view->markers = $markers;        
    }
    
}
